package com.flink.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.flink.api.common.functions.RuntimeContext;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.types.Row;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.Serializable;

/**
 * @Description TODO
 * @Author li
 * @Date 2021/8/25 3:44 下午
 */
public class ElasticSearchSinkDTO implements ElasticsearchSinkFunction<Row>, Serializable {
    private String index;
    private String type;
    private String[] columns;

    public ElasticSearchSinkDTO(String index, String type, String[] columns) {
        this.index = index;
        this.type = type;
        this.columns = columns;
    }

    public IndexRequest createIndexRequest(Row element) {
        JSONObject jsonObject = new JSONObject();
        for (int i = 0; i < element.getArity(); i++) {
            jsonObject.put(columns[i], element.getField(i).toString());
        }
        System.out.println(jsonObject.toJSONString());
        return Requests.indexRequest()
                .index(index)
                .type(type)
                .source(jsonObject, XContentType.JSON);
    }

    @Override
    public void process(Row row, RuntimeContext runtimeContext, RequestIndexer requestIndexer) {
        System.out.println(row.toString());
        requestIndexer.add(createIndexRequest(row));
    }
}
